package com.winexpress.session.product;

import com.winexpress.entity.Rating;
import com.winexpress.entity.User;
import com.winexpress.entity.Wine;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@LocalBean
@Stateless
public class RatingSessionBean {

    @PersistenceContext
    private EntityManager em;

//  public Long createRating(long uid, long wid, int rating) {
    public Long createRating(RatingMessage inMessage) {
        long uid = inMessage.getUid();
        long wid = inMessage.getWid();
        int rating = inMessage.getRating();

        Rating newRating = new Rating();

        User u = em.find(User.class, uid);

        newRating.setUid(u);
        newRating.setRating(rating);

        em.persist(newRating);
        em.flush();

        Wine w = em.find(Wine.class, wid);
        List<Rating> list = w.getRating();
        list.add(newRating);
        w.setRating(list);

        em.persist(w);
        em.flush();

        return newRating.getId();
    }

    public double getAverageRating(Long wid) {
        Wine w = em.find(Wine.class, wid);
        List<Rating> list = w.getRating();
        float sum = 0;
        for (Rating r : list) {
            sum = sum + r.getRating();
        }
        if (list.isEmpty()) {
            return 0;
        } else {
            return sum / list.size();
        }
    }
}
